{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 数字\n",
    "a1 = 100      # 正整数\n",
    "b1 = 0xa5bc3  # 十六进制\n",
    "b2 = 0b1101   # 二进制\n",
    "b3 = 0o177   # 八进制\n",
    "c1 = 12.3e9  # 浮点数\n",
    "c2 = 1.2e-05 # 浮点数\n",
    "d1 = 4+3j   # 虚数\n",
    "from fractions import Fraction\n",
    "e1 = Fraction(3,4)  # 分数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 数字运算符\n",
    "30 + 40 # 70  加法\n",
    "15 - 8  # 7   减法\n",
    "15 * 2  # 30  乘法\n",
    "15 / 2  # 7.5 除法\n",
    "9 // 4  # 2   取整除\n",
    "9 % 4   # 1   取余\n",
    "4 ** 2  # 16  幂"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 赋值运算符\n",
    "a = 1 + 3 # 4 把=号右边的结果给左边的变量\n",
    "a += 1    # 5 加法赋值运算符, 等效 a = a + 1\n",
    "a -= 1    # 4 减法赋值运算符, 等效 a = a - 1\n",
    "a *= 2    # 8 乘法赋值运算符, 等效 a = a * 2\n",
    "a /= 2    # 4 除法赋值运算符, 等效 a = a / 2\n",
    "a %= 5    # 4 取模赋值运算符, 等效 a = a % 5\n",
    "a **= 3   # 64 幂赋值运算符, 等效 a = a ** 3\n",
    "a //= 3   # 21 取整除赋值运算符, 等效 a = a // 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 常见字符串常量和表达式\n",
    "S1 = ''                                  # 空字符串\n",
    "S2 = \"spam’s\"                           # 双引号和单引号相同\n",
    "S3 = \"s\\np\\ta\\x00m\"                      # 转义字符\n",
    "S4 = \"\"\"spam\"\"\"                          # 三重引号字符串，一般用于函数说明\n",
    "S5 = r'\\temp'                            # Raw字符串，不会进行转义，抑制转义\n",
    "S6 = b'Spam'                             # Python3中的字节字符串\n",
    "S7 = u'spam'                             # Python2.6中的Unicode字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 字符串操作\n",
    "s1='123'\n",
    "s2='abcd'\n",
    "s3=' hello world '\n",
    "print(s1+s2)\n",
    "print(s1*2)\n",
    "print(s1[0], s2[0:3], len(s1))\n",
    "print(s2.find('b'))\n",
    "print(s3.strip())\n",
    "print(s2.split('b'))\n",
    "print(s1.isdigit())\n",
    "print(s2.endswith('cd'))\n",
    "print(s3.replace('hello', 'hi'))\n",
    "# 字符串迭代，成员关系\n",
    "print('----成员关系----')\n",
    "for x in s1:\n",
    "    print(x)\n",
    "print([i*2 for i in s2]) # ['aa', 'bb', 'cc', 'dd']\n",
    "print('----字符串的合并----')\n",
    "# 字符串输出，结果：a,b,c,d\n",
    "print(','.join(s2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- Python中的字符串格式化实现1--字符串格式化表达式\n",
    "    \"\"\"\n",
    "    基于C语言的'print'模型，并且在大多数的现有的语言中使用。\n",
    "    通用结构：%[(name)][flag][width].[precision]typecode\n",
    "    \"\"\"\n",
    "    \"this is %d %s bird\" % (1, 'dead')                          # 一般的格式化表达式\n",
    "    \"%s---%s---%s\" % (42, 3.14, [1, 2, 3])                      # 字符串输出：'42---3.14---[1, 2, 3]'\n",
    "    \"%d...%6d...%-6d...%06d\" % (1234, 1234, 1234, 1234)         # 对齐方式及填充：\"1234...  1234...1234  ...001234\"\n",
    "    x = 1.23456789\n",
    "    \"%e | %f | %g\" % (x, x, x)                                  # 对齐方式：\"1.234568e+00 | 1.234568 | 1.23457\"\n",
    "    \"%6.2f*%-6.2f*%06.2f*%+6.2f\" % (x, x, x, x)                 # 对齐方式：'  1.23*1.23  *001.23* +1.23'\n",
    "    \"%(name1)d---%(name2)s\" % {\"name1\":23, \"name2\":\"value2\"}    # 基于字典的格式化表达式\n",
    "    \"%(name)s is %(age)d\" % vars()                              # vars()函数调用返回一个字典，包含了所有本函数调用时存在的变量\n",
    "    \n",
    "#-- Python中的字符串格式化实现2--字符串格式化调用方法\n",
    "    # 普通调用\n",
    "    \"{0}, {1} and {2}\".format('spam', 'ham', 'eggs')            # 基于位置的调用\n",
    "    \"{motto} and {pork}\".format(motto = 'spam', pork = 'ham')   # 基于Key的调用\n",
    "    \"{motto} and {0}\".format('ham', motto = 'spam')             # 混合调用\n",
    "    # 添加键 属性 偏移量 (import sys)\n",
    "    \"my {1[spam]} runs {0.platform}\".format(sys, {'spam':'laptop'})                 # 基于位置的键和属性\n",
    "    \"{config[spam]} {sys.platform}\".format(sys = sys, config = {'spam':'laptop'})   # 基于Key的键和属性\n",
    "    \"first = {0[0]}, second = {0[1]}\".format(['A', 'B', 'C'])                       # 基于位置的偏移量\n",
    "    # 具体格式化\n",
    "    \"{0:e}, {1:.3e}, {2:g}\".format(3.14159, 3.14159, 3.14159)   # 输出'3.141590e+00, 3.142e+00, 3.14159'\n",
    "    \"{fieldname:format_spec}\".format(......)\n",
    "    # 说明:\n",
    "    \"\"\"\n",
    "        fieldname是指定参数的一个数字或关键字, 后边可跟可选的\".name\"或\"[index]\"成分引用\n",
    "        format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]\n",
    "        fill        ::=  <any character>              #填充字符\n",
    "        align       ::=  \"<\" | \">\" | \"=\" | \"^\"        #对齐方式\n",
    "        sign        ::=  \"+\" | \"-\" | \" \"              #符号说明\n",
    "        width       ::=  integer                      #字符串宽度\n",
    "        precision   ::=  integer                      #浮点数精度\n",
    "        type        ::=  \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n",
    "    \"\"\"\n",
    "    # 例子:\n",
    "        '={0:10} = {1:10}'.format('spam', 123.456)    # 输出'=spam       =    123.456'\n",
    "        '={0:>10}='.format('test')                    # 输出'=      test='\n",
    "        '={0:<10}='.format('test')                    # 输出'=test      ='\n",
    "        '={0:^10}='.format('test')                    # 输出'=   test   ='\n",
    "        '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)   # 输出'FF, 377, 11111111'\n",
    "        'My name is {0:{1}}.'.format('Fred', 8)       # 输出'My name is Fred    .'  动态指定参数\n",
    "#-- Python中的字符串格式化实现3-格式化字符串常量(Python3.6及以后的版本可用)\n",
    "    # 普通调用\n",
    "    L=[1,2,3]\n",
    "    f\"列表第一个元素是{L[0]}\"        # 字符串输出：'列表第一个元素是1'\n",
    "    # 算术和函数调用\n",
    "    f'24*8+4={24 * 8 + 4}'           # 字符串输出：'24*8+4=196'\n",
    "    f\"列表长度为{len(l)}\"            # 字符串输出：'列表长度为3'\n",
    "    f\"列表长度为{{len(l)}}\"          # 字符串输出: '列表长度为{len(l)}'\n",
    "    # 格式类型\n",
    "    a = 128\n",
    "    f'{a:x}'                        # 十六进制 字符串输出：'80'\n",
    "    f'{a:o}'                        # 八进制 字符串输出：'200'\n",
    "    f'{a:b}'                        # 二进制 字符串输出：'10000000'\n",
    "    import datetime\n",
    "    d =  datetime.datetime.strptime('2020-02-14','%Y-%m-%d')\n",
    "    f'{d:%a}'            # 星期几（缩写）字符串输出：'Fri'\n",
    "    f'{d:%w}'            # 星期几（数字，0 是周日，6 是周六）字符串输出：'5'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 内置str处理函数：\n",
    "    str1 = \"stringobject\"\n",
    "    # 全部大写，全部小写、大小写转换，首字母大写，每个单词的首字母都大写\n",
    "    str1.upper(); str1.lower(); str1.swapcase(); str1.capitalize(); str1.title()        \n",
    "    str1.ljust(width)                       # 获取固定长度，左对齐，右边不够用空格补齐\n",
    "    str1.rjust(width)                       # 获取固定长度，右对齐，左边不够用空格补齐\n",
    "    str1.center(width)                      # 获取固定长度，中间对齐，两边不够用空格补齐\n",
    "    str1.zfill(width)                       # 获取固定长度，右对齐，左边不足用0补齐\n",
    "    str1.find('t',start,end)                # 查找字符串，可以指定起始及结束位置搜索\n",
    "    str1.rfind('t')                         # 从右边开始查找字符串\n",
    "    str1.count('t')                         # 查找字符串出现的次数\n",
    "    #上面所有方法都可用index代替，不同的是使用index查找不到会抛异常，而find返回-1\n",
    "    str1.replace('old','new')               # 替换函数，替换old为new，参数中可以指定maxReplaceTimes，即替换指定次数的old为new\n",
    "    str1.strip();                           # 默认删除空白符\n",
    "    str1.strip('d');                        # 删除str1字符串中开头、结尾处，位于 d 删除序列的字符\n",
    "    str1.lstrip();\n",
    "    str1.lstrip('d');                       # 删除str1字符串中开头处，位于 d 删除序列的字符\n",
    "    str1.rstrip();\n",
    "    str1.rstrip('d')                        # 删除str1字符串中结尾处，位于 d 删除序列的字符\n",
    "    str1.startswith('start')                # 是否以start开头\n",
    "    str1.endswith('end')                    # 是否以end结尾\n",
    "    # 判断字符串是否全为字符、数字、小写、大写\n",
    "    str1.isalnum(); str1.isalpha(); str1.isdigit(); str1.islower(); str1.isupper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 常用列表常量和操作，需要逐个运行，这里是展示\n",
    "L = [[1, 2], 'string', {}]                        # 嵌套列表\n",
    "L = list('spam')                                  # 列表初始化\n",
    "L = list(range(0, 4))                             # 列表初始化\n",
    "len(L)                                            # 求列表长度\n",
    "L.count(value)                                    # 求列表中某个值的个数\n",
    "L.append(obj)                                     # 向列表的尾部添加数据，比如append(2)，添加元素2\n",
    "L.insert(index, obj)                              # 向列表的指定index位置添加数据，index及其之后的数据后移\n",
    "L.extend(interable)                               # 通过添加iterable中的元素来扩展列表，比如extend([2])，添加元素2，注意和append的区别\n",
    "L.index(value, [start, [stop]])                   # 返回列表中值value的第一个索引\n",
    "L.pop([index])                                    # 删除并返回index处的元素，默认为删除并返回最后一个元素\n",
    "L.remove(value)                                   # 删除列表中的value值，只删除第一次出现的value的值\n",
    "L.reverse()                                       # 反转列表\n",
    "L.sort(cmp=None, key=None, reverse=False)       # 排序列表\n",
    "a = [1, 2, 3], b = a[10:]                         # 注意，这里不会引发IndexError异常，只会返回一个空的列表[]\n",
    "a = [], a += [1]                                  # 这里实在原有列表的基础上进行操作，即列表的id没有改变\n",
    "a = [], a = a + [1]                               # 这里最后的a要构建一个新的列表，即a的id发生了变化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 常用字典常量和操作，这里不能直接运行\n",
    "D = {}\n",
    "D = {'spam':2, 'tol':{'ham':1}}                   # 嵌套字典\n",
    "D = dict.fromkeys(['s', 'd'], 8)                  # {'s': 8, 'd': 8}\n",
    "D = dict(name = 'tom', (3,4) = 7)                  # {'age': 12, 'name': 'tom'}\n",
    "D = dict([('name', 'tom'), ('age', 12)])          # {'age': 12, 'name': 'tom'}\n",
    "D = dict(zip(['name', 'age'], ['tom', 12]))       # {'age': 12, 'name': 'tom'}\n",
    "D.keys(); D.values(); D.items()                   # 字典键、值以及键值对\n",
    "D.get(key, default)                               # get函数\n",
    "D.update(D_other)                                 # 合并字典，如果存在相同的键值，D_other的数据会覆盖掉D的数据\n",
    "D.pop(key, [D])                                   # 删除字典中键值为key的项，返回键值为key的值，如果不存在，返回默认值D，否则异常\n",
    "D.popitem()                                       # pop字典中随机的一项（一个键值对）\n",
    "del D                                             # 删除字典\n",
    "del D['key']                                      # 删除字典的某一项\n",
    "if key in D:   if key not in D:                   # 测试字典键是否存在\n",
    "# 字典注意事项：（1）对新索引赋值会添加一项（2）字典键不一定非得是字符串，也可以为任何的不可变对象\n",
    "# 不可变对象：调用对象自身的任意方法，也不会改变该对象自身的内容，这些方法会创建新的对象并返回。\n",
    "# 字符串、整数、tuple都是不可变对象，dict、set、list都是可变对象\n",
    "D[(1,2,3)] = 2                                    # tuple作为字典的key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#-- 集合set，不能直接运行\n",
    "\"\"\"\n",
    "set是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素。\n",
    "set支持union(联合), intersection(交), difference(差)和symmetric difference(对称差集)等数学运算。\n",
    "set支持x in set, len(set), for x in set。\n",
    "set不记录元素位置或者插入点, 因此不支持indexing, slicing, 或其它类序列的操作\n",
    "\"\"\"\n",
    "s = set([3,5,9,10])                          # 创建一个数值集合，返回{3, 5, 9, 10}\n",
    "t = set(\"Hello\")                             # 创建一个字符的集合，返回{'l', 'H', 'e', 'o'}\n",
    "a = t | s;    t.union(s)                     # t 和 s的并集\n",
    "b = t & s;    t.intersection(s)              # t 和 s的交集\n",
    "c = t - s;  t.difference(s)                # 求差集（项在t中, 但不在s中）\n",
    "d = t ^ s;    t.symmetric_difference(s)      # 对称差集（项在t或s中, 但不会同时出现在二者中）\n",
    "t.add('x');   t.remove('H')                  # 增加/删除一个item\n",
    "s.update([10,37,42])                         # 利用[......]更新s集合\n",
    "'x' in s,  'x' not in s                          # 集合中是否存在某个值\n",
    "s.issubset(t);      s <= t                   # 测试是否 s 中的每一个元素都在 t 中\n",
    "s.issuperset(t);    s >= t                   # 测试是否 t 中的每一个元素都在 s 中 \n",
    "s.copy(); \n",
    "s.discard('x');                                # 删除s中x\n",
    "s.clear()                                    # 清空s\n",
    "{x**2 for x in [1, 2, 3, 4]}                 # 集合解析，结果：{16, 1, 4, 9}\n",
    "{x for x in 'spam'}                          # 集合解析，结果：{'a', 'p', 's', 'm'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 异常处理\n",
    "try:\n",
    "    #运行别的代码\n",
    "    f = open(\"testfile\", \"w\")\n",
    "    f.write(\"这是一个测试文件，用于测试异常!!\")\n",
    "except IOError: # IOError 是异常类型\n",
    "    #如果在try部份引发了'name'异常\n",
    "    print(\"Error: 没有找到文件或读取文件失败\")\n",
    "else:\n",
    "    #如果没有异常发生\n",
    "    print(\"内容写入文件成功\")\n",
    "finally:\n",
    "    #退出try时总会执行\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 文件读写\n",
    "f = open('/readme.txt', 'r', encoding = 'UTF-8') # 打开文件\n",
    "content = f.read()  # 读文件\n",
    "f.close() # 关闭文件\n",
    "# 使用这种方式打开文件，可以不使用close()关闭文件\n",
    "with open('/readme.txt', 'r+') as f: \n",
    "    content = f.readlines()  # 以列表的方式读取文件内容\n",
    "    f.write('python')        # 清空文件内容，并写入字符串入内容"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
